package Logic;

import java.util.ArrayList;

import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import Model.Approval;
import Model.Staff;

public class EmailerJob implements Job {
	public void execute(JobExecutionContext context)
			throws JobExecutionException {

		// get all old pending appointments
		ArrayList<Approval> pendingAppt = new ArrayList<Approval>();
		pendingAppt = Database.StaffAppointmentDB
				.getAllOldPendingAppointments("4");
		
		// get list (names and email) of approvers
		ArrayList<Staff> approvers = new ArrayList<Staff>();
		approvers = Database.StaffDB.getApproverList();
		
		// get count of old pending appointments
		int count = Database.StaffAppointmentDB.countAllOldPendingAppointments();
		
		// get list of pending appointment names
		// concat approvers email to pass into recipient
		// format email table
		System.out.println("***** Get list of approvers *****");
		//for loop to see approvers retrieved
		for (int i=0; i < approvers.size(); i++){
			System.out.println("Approver: " + approvers.get(i).getName());
			System.out.println("Approver email: " + approvers.get(i).getEmail());
		}
		
		System.out.println("");
		System.out.println("***** Get list of outstanding pending appointments *****");
		//for loop to see records retrieved
		for (int i = 0; i < pendingAppt.size(); i++) {
			System.out.println("User: " + pendingAppt.get(i).getName()
					+ " is still pending approval");	
		}
		
		System.out.println("Total number of outstanding pending appointments: " + count);
		System.out.println("");

		//declare email body content
		//	String body = "Dear" + "Hi";
		
		// send email here
		// get list (name and email) of approvers
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");

		Session session = Session.getDefaultInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(
								"senderemailhere", "password");
					}
				});

		try {
			// create the message.
		      MimeMessage mimeMessage = new MimeMessage(session);
		 
		      MimeMultipart rootMixedMultipart = new MimeMultipart("mixed");
		      mimeMessage.setContent(rootMixedMultipart);
		 
		      MimeMultipart nestedRelatedMultipart = new MimeMultipart("related");
		      MimeBodyPart relatedBodyPart = new MimeBodyPart();
		      relatedBodyPart.setContent(nestedRelatedMultipart);
		      rootMixedMultipart.addBodyPart(relatedBodyPart);
		 
		      MimeMultipart messageBody = new MimeMultipart("alternative");
		      MimeBodyPart bodyPart = null;
		      for (int i = 0; i < nestedRelatedMultipart.getCount(); i++) {
		          BodyPart bp = nestedRelatedMultipart.getBodyPart(i);
		          if (bp.getFileName() == null) {
		              bodyPart = (MimeBodyPart) bp;
		          }
		      }
		      if (bodyPart == null) {
		          MimeBodyPart mimeBodyPart = new MimeBodyPart();
		          nestedRelatedMultipart.addBodyPart(mimeBodyPart);
		          bodyPart = mimeBodyPart;
		      }
		      bodyPart.setContent(messageBody, "text/alternative");
		      
		      String text = "Dear approver, <br><br> You have " + count + " outstanding appointments pending for approval! <br><br> Please review them <a href=\"http://localhost:8080/QMS_11Dec/staffapp_approve.jsp\">here</a> ASAP. <br><br>"
		    		  +"Regards, <br> QMS Administrator"
		    		  //+"<table border=\"1\"><tr><th>Staff</th><th>Number of days since appointment</th></tr>"
		    		  //+" "
		    		  //+ "</table>"
		    		  +"";
		 
		      // Create the HTML text part of the message.
		      MimeBodyPart htmlTextPart = new MimeBodyPart();
		      htmlTextPart.setContent(text, "text/html;charset=UTF-8");
		      messageBody.addBodyPart(htmlTextPart);
		 
		      mimeMessage.setReplyTo(new InternetAddress[]{new InternetAddress("senderemailhere")});
		      mimeMessage.setFrom(new InternetAddress("senderemailhere"));
		      mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("passInConcatStringHere"));
		      mimeMessage.setSubject("Reminder: Outstanding Pending Appointments");
		      Transport.send(mimeMessage);

			System.out.println("Email sent successfully.");

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}
